package Spring_cloud_firstdemo.cloud_mysql_demo.controllers;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.annotation.Resource;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import Spring_cloud_firstdemo.cloud_mysql_demo.models.User;


@RestController
@Controller
public class MainController {
	@RequestMapping("/t")
	@ResponseBody
	public ArrayList<User> showtable() {
		System.out.println("show table.....");
		return service();
	}

	
	@Resource
	private JdbcTemplate jdbcTemplate;

	public ArrayList<User> service() {
		
		String sql = "select * from users";
		@SuppressWarnings({ "rawtypes", "unchecked" })
		ArrayList<User> result = (ArrayList<User>) jdbcTemplate.query(sql, new ResultSetExtractor() {

			public ArrayList extractData(ResultSet rs) throws SQLException, DataAccessException {
				ArrayList<User> result = new ArrayList<User>();
				while (rs.next()) {
					User user = new User();
					user.setId(rs.getLong(1));
					user.setEmail(rs.getString(2));
					user.setName(rs.getString(3));
					// System.out.println(user.getId());
					// System.out.println(user.getEmail());
					// System.out.println(user.getName());
					result.add(user);
				}
				return result;
			}

		});
		return result;
	}
}
